package cn.javacv.gulimall.product.service.impl;

import cn.javacv.gulimall.common.constant.ProductConstant;
import cn.javacv.gulimall.product.dao.AttrAttrgroupRelationDao;
import cn.javacv.gulimall.product.dao.AttrDao;
import cn.javacv.gulimall.product.dao.AttrGroupDao;
import cn.javacv.gulimall.product.dao.CategoryDao;
import cn.javacv.gulimall.product.entity.AttrAttrgroupRelationEntity;
import cn.javacv.gulimall.product.entity.AttrGroupEntity;
import cn.javacv.gulimall.product.entity.CategoryEntity;
import cn.javacv.gulimall.product.service.CategoryService;
import cn.javacv.gulimall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.javacv.gulimall.common.utils.PageUtils;
import cn.javacv.gulimall.common.utils.Query;

import cn.javacv.gulimall.product.entity.AttrEntity;
import cn.javacv.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        if (attr.getType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrEntity.getGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, long catelogId, String type) {
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.eq("type","base".equalsIgnoreCase(type)?1:0);
        if (catelogId != 0) {
            attrEntityQueryWrapper.eq("category_id",catelogId);
        }
        Object key = params.get("key");
        if (key!= null && StringUtils.isNotEmpty(key.toString())){
            attrEntityQueryWrapper.and((wrapper)->{
                wrapper.eq("id",key.toString()).or().like("name",key.toString());
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> attrEntityList = page.getRecords();
        List<AttrVO> attrVOList = attrEntityList.stream().map(attrEntity -> {
            AttrVO attrVO = new AttrVO();
            BeanUtils.copyProperties(attrEntity,attrVO);
            //设置分类 分组的名字
            //AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getId()));
            if ("base".equalsIgnoreCase(type)) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrEntity.getGroupId());
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCategoryId());
                if (null != categoryEntity) {
                    attrVO.setCategoryName(categoryEntity.getName());
                }
                if (null != attrGroupEntity) {
                    attrVO.setGroupName(attrGroupEntity.getName());
                }
            }
            return attrVO;
        }).collect(Collectors.toList());
        pageUtils.setList(attrVOList);
        return pageUtils;
    }

    @Override
    public AttrVO getAttrInfoById(Long id) {
        AttrVO attrVO = new AttrVO();
        AttrEntity attrEntity = this.getById(id);
        BeanUtils.copyProperties(attrEntity,attrVO);
        Long [] pathArr = categoryService.findCategoryPath(attrEntity.getCategoryId());
        attrVO.setCatelogPath(pathArr);
        if (attrVO.getType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrEntity.getGroupId());
            if (null != attrGroupEntity) {
                attrVO.setGroupName(attrGroupEntity.getName());
            }
        }
        return attrVO;
    }

    @Override
    public void updateAttrById(AttrVO attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO,attrEntity);
        this.updateById(attrEntity);
        if (attrVO.getType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrEntity.getGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getId());
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getId()));
            if (null != count && count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIdList = attrAttrgroupRelationEntities.stream().map( (attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
                })
        ).collect(Collectors.toList());
        if (attrIdList.isEmpty()){
            return new ArrayList<>();
        }
        return this.listByIds(attrIdList);
    }

    @Override
    public List<AttrEntity> getNoRelationList(long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIdList = attrAttrgroupRelationEntities.stream().map( (attrAttrgroupRelationEntity -> {
                    return attrAttrgroupRelationEntity.getAttrId();
                })
        ).collect(Collectors.toList());
        return this.list(new QueryWrapper<AttrEntity>().notIn("id",attrIdList));
    }

    @Override
    public PageUtils getNoRelationPage(Map<String, Object> params, long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIdList = attrAttrgroupRelationEntities.stream().map( (attrAttrgroupRelationEntity -> {
                    return attrAttrgroupRelationEntity.getAttrId();
                })
        ).collect(Collectors.toList());
        if (attrIdList.size()>0) {
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    new QueryWrapper<AttrEntity>().notIn("id", attrIdList)
            );
            return new PageUtils(page);
        }else {
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    new QueryWrapper<AttrEntity>()
            );
            return new PageUtils(page);
        }
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIdList) {
        List<Long> attrEntityList = baseMapper.selectSearchAttrs(attrIdList);
        return attrEntityList;
    }

}
